package com.itrui.buyitbackend.controller;

import com.itrui.buyitbackend.common.Code;
import com.itrui.buyitbackend.common.Result;
import com.itrui.buyitbackend.pojo.Business;
import com.itrui.buyitbackend.pojo.User;
import com.itrui.buyitbackend.service.BusinessService;
import com.sun.org.apache.bcel.internal.generic.ACONST_NULL;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestController
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    /**
     * 登录功能
     * @param business
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Business business){
        try{
            Business myBusiness = businessService.login(business.getBusinessAccount());
            if (!myBusiness.getBusinessPassword().equals(business.getBusinessPassword())){
                return new Result(Code.GET_ERR,"密码错误");
            }else {
                return new Result(Code.GET_OK,"登录成功");
            }
        }catch (Exception e){
            if (e.toString().equals("java.lang.NullPointerException")){
                return new Result(Code.GET_ERR,"账号不存在");
            }
        }
        return null;
    };

    /**
     *商户注册
     * @param business
     * @return
     */
    @PostMapping("/register")
    public Result businessRegister(@RequestBody Business business){
        boolean flag = false;
        log.info("商家注册信息："+business.toString());
        try {
            flag = businessService.businessRegister(business);
        }catch (Exception e){

            log.info("错误信息："+e.toString());
            if (e.toString().equals("org.springframework.dao.DuplicateKeyException:")){
                return new Result(Code.SAVE_ERR,"账号重复");
            }

        }
        return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR,flag?"注册成功":"注册失败");
    };

    @GetMapping("/{id}")
    public Business getBusinessInfo(@PathVariable Integer id){
        System.out.println(id);
        Business businessInfo = businessService.getBusinessInfo(id);
        System.out.println(businessInfo);
        return businessInfo;
    };

}
